package cn.edu.fzu.homemaking.wallet.filter;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.fzu.homemaking.common.SessionConstant;
import cn.edu.fzu.homemaking.util.ResultUtil;
import cn.edu.fzu.homemaking.wallet.domain.dto.User;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.core.annotation.Order;

import cn.edu.fzu.homemaking.wallet.api.SsoApi;
import cn.edu.fzu.homemaking.web.Result;
import cn.edu.fzu.homemaking.web.RetCode;

@Order(2)
@WebFilter(urlPatterns = "/api/wallet/*")
public class AuthFilter implements Filter {

    @Resource
    private SsoApi ssoApi;

    @Override
    public void init(FilterConfig filterConfig) {
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();

        Result login = ssoApi.isLogin();
        if (login.getCode() != RetCode.SUCCESS) {
            //返回前端登陆报错信息，比如账号被异地登陆踢出
            respWriter(resp, new Result(RetCode.REFUSE_LOGIN, null, login.getMessage(), null));
            return;
        }
        if (!(boolean) login.getValue()) {
            //返回登陆页面给前端
            String loginUrl = (String) ssoApi.loginIndex(null).getValue();
            respWriter(resp, new Result(RetCode.NO_LOGIN, null, null, loginUrl));
            return;
        }
        Result result = ssoApi.getSession(SessionConstant.ACCOUNT);
        User user = ResultUtil.parseValue(result, User.class);
        session.setAttribute(SessionConstant.ACCOUNT, user);
        session.setAttribute(SessionConstant.USER_TYPE,
                (String) ssoApi.getSession(SessionConstant.USER_TYPE).getValue());
        chain.doFilter(req, resp);
    }


    @Override
    public void destroy() {
        // do nothing
    }


    private void respWriter(HttpServletResponse resp, Result result) throws IOException {
        resp.getWriter().print(JSON.toJSONString(result));
    }
}
